package init

import (
	"context"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"server/basic/config"
)

func init() {
	Mysql()
	Redis()
	Es()
}

func Es() {
	var err error
	cfg := elasticsearch.Config{
		Addresses: []string{

			"http://14.103.129.201:9200",
		},
		// ...

	}
	config.Es, err = elasticsearch.NewClient(cfg)
	if err != nil {
		return
	}
}

func Redis() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     "14.103.149.201:6379",
		Password: "e10adc3949ba59abbe56e057f20f883e", // no password set
		DB:       0,                                  // use default DB
	})

	err := config.Rdb.Set(context.Background(), "sss", "value", 0).Err()
	if err != nil {
		panic(err)
	}
}

func Mysql() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:e10adc3949ba59abbe56e057f20f883e@tcp(14.103.149.201:3306)/day17?charset=utf8mb4&parseTime=True&loc=Local"
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return
	}
	fmt.Println("数据库连接成功")
}
